//
//  LSChatKeyboard.m
//  LookScore
//
//  Created by wws on 2018/3/22.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSChatKeyboard.h"

//frame
#define Frame(x,y,width,height)  CGRectMake(x, y, width, height)

//最大最小值
#define MaxX(frame) CGRectGetMaxX(frame)
#define MaxY(frame) CGRectGetMaxY(frame)
#define MinX(frame) CGRectGetMinX(frame)
#define MinY(frame) CGRectGetMinY(frame)
//宽度高度
#define Width(frame)    CGRectGetWidth(frame)
#define Height(frame)   CGRectGetHeight(frame)
@interface LSChatKeyboard()<UITextViewDelegate,UIScrollViewDelegate>
@property (nonatomic, copy) ChatTextMessageSendBlock textCallback;
@property (nonatomic ,copy) ChatBoardChangeBlock changHback;
@property (nonatomic, strong) id target;

//send按钮
@property (nonatomic, strong) UIButton *swtHandleButton;
//顶部消息操作栏
@property (nonatomic, strong) UIView *messageBar;
@end


@implementation LSChatKeyboard
//记录当前键盘的高度 ，键盘除了系统的键盘还有咱们自定义的键盘，互相来回切换
static CGFloat keyboardHeight         = 0;
static const CGFloat defaultMsgBarHeight = 49;  //模态输入框容器 49
static const CGFloat defaultInputHeight     = 35; //默认输入框 35
//输入栏
- (UIView *)messageBar{
    if (!_messageBar) {
        _messageBar = [[UIView alloc]init];
        _messageBar.backgroundColor = LSBackGroundColor;
        [_messageBar addSubview:self.msgTextView];
        [_messageBar addSubview:self.swtHandleButton];
    }
    return _messageBar;
}
//输入框
- (UITextView *)msgTextView{
    if (!_msgTextView) {
        _msgTextView = [[UITextView alloc]init];
        _msgTextView.font = LSFontSize13;
        _msgTextView.showsVerticalScrollIndicator = NO;
        _msgTextView.showsHorizontalScrollIndicator = NO;
        _msgTextView.returnKeyType = UIReturnKeySend;
        _msgTextView.enablesReturnKeyAutomatically = YES;
        _msgTextView.placeholderColor = LSTitleGrayColor2;
        _msgTextView.delegate = self;
//        ViewRadius(_msgTextView, 5);
        //观察者监听高度变化
        [_msgTextView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    return _msgTextView;
}

//切换操作键盘
- (UIButton *)swtHandleButton{
    if (!_swtHandleButton) {
        _swtHandleButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _swtHandleButton.titleLabel.font = LSFontSize12;
        _swtHandleButton.backgroundColor = LSSubColor9dd3cc;
        [_swtHandleButton setTitle:@"发送" forState:UIControlStateNormal];
        [_swtHandleButton addTarget:self action:@selector(switchHandleKeyboard:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _swtHandleButton;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self addSubview:self.messageBar];
        [self configUI];
    }
    return self;
}

- (void)configUI{
    self.messageBar.frame = CGRectMake(0, 0, LSScreenWidth, defaultMsgBarHeight);
    self.msgTextView.frame = CGRectMake(8, 0, LSScreenWidth-90, defaultInputHeight);
    self.swtHandleButton.layer.cornerRadius = 2;
    self.swtHandleButton.layer.masksToBounds = YES;
//    self.swtHandleButton.frame = CGRectMake(CGRectGetMaxX(self.msgTextView.frame)+10, 5,60, 35);
    self.swtHandleButton.sd_layout
    .leftSpaceToView(self.self.msgTextView, 10)
    .centerYEqualToView(self.msgTextView)
    .widthIs(60)
    .heightIs(defaultInputHeight);
    
}
#pragma mark - 系统键盘即将弹起
- (void)systemKeyboardWillShow:(NSNotification *)note{
    NSInteger KeyH = 0;
    if (_type == 1) {
        KeyH = 100 + LSScareValue(200, LSScreenWidth) -LSNavBarHeight;
    }else{
        KeyH = LSNavBarHeight;
        
    }
    //重置所有按钮selected
    [self reloadSwitchButtons];
    //获取系统键盘高度
    CGFloat systemKbHeight  = [note.userInfo[@"UIKeyboardBoundsUserInfoKey"]CGRectValue].size.height;
    //记录系统键盘高度
    keyboardHeight = systemKbHeight;
    //将自定义键盘跟随位移
    //300
    [self customKeyboardMove:LSScreenHeight-KeyH - systemKbHeight -CGRectGetHeight(self.messageBar.frame)];
    if (self.changHback) {
        self.changHback(systemKbHeight);
    }
}
#pragma mark - 切换按钮初始化
- (void)reloadSwitchButtons{
    
    self.swtHandleButton.selected = NO;
}
#pragma mark - 自定义键盘位移变化
- (void)customKeyboardMove:(CGFloat)customKbY{
//    MyLog(@"customer= %f",customKbY);
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0,customKbY, LSScreenWidth, CGRectGetHeight(self.frame));
      
    }];
}
- (void)switchHandleKeyboard:(UIButton *)swtHandleButton{
    [self sendTextMessage];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    //删除键监听
    if ([text isEqualToString:@""""]) {
        
        MyLog(@"----------------点击了系统键盘删除键");
        //系统键盘删除
        [self keyboardDelete];
        return NO;
        
        //发送键监听
    }else if ([text isEqualToString:@"\n"]){
        
        //发送普通文本消息
        [self sendTextMessage];
        return NO;
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if ([LSAccountArchive isLogin]) {
        return YES;
    }else{
        self.block();
        return NO;
    }
    
    
}

#pragma mark - 监听输入框变化 (这里如果放到layout里自动让他布局 , 会稍显麻烦一些 , 所以自动手动控制一下)
//这里用contentSize计算较为简单和精确 , 如果计算文字高度 ,  还需要加上textView的内间距.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    CGFloat oldHeight  = [change[@"old"]CGSizeValue].height;
    CGFloat newHeight = [change[@"new"]CGSizeValue].height;
    if (oldHeight <=0 || newHeight <=0) return;
    
    if (newHeight != oldHeight) {
        MyLog(@"高度变化");
        //根据实时的键盘高度进行布局
        CGFloat inputHeight = newHeight > defaultInputHeight ? newHeight : defaultInputHeight;
        [self msgTextViewHeightFit:inputHeight];
    }
}
#pragma mark - 输入框高度调整
- (void)msgTextViewHeightFit:(CGFloat)msgViewHeight{
    self.messageBar.frame = Frame(0, 0, LSScreenWidth, msgViewHeight +MinY(self.msgTextView.frame)*2);
    self.msgTextView.frame = Frame(MinX(self.msgTextView.frame),(Height(self.messageBar.frame)-msgViewHeight)*0.5, Width(self.msgTextView.frame), msgViewHeight);
}

#pragma mark - 键盘删除内容
- (void)keyboardDelete{
    
    NSMutableString *txtStrM = [[NSMutableString alloc]initWithString:self.msgTextView.text];
    //当前光标位置
    NSInteger location = self.msgTextView.selectedRange.location;
    if (!txtStrM.length) return;
    
    //正则检测是否存在表情
    NSRegularExpression *pression = [NSRegularExpression regularExpressionWithPattern:@"\\[[^\\[\\]]*\\]" options:NSRegularExpressionCaseInsensitive error:NULL];
    NSArray *results = [pression matchesInString:self.msgTextView.text options:NSMatchingReportProgress range:NSMakeRange(0, self.msgTextView.text.length)];
    //检测光标前是否有表情
    __block BOOL deleteEmotion = NO;
    [results enumerateObjectsUsingBlock:^(NSTextCheckingResult  *_Nonnull checkResult, NSUInteger idx, BOOL * _Nonnull stop) {
        //光标前面有表情
        if (checkResult.range.location + checkResult.range.length == location) {
            
            MyLog(@"-------光标前是表情------------");
            [txtStrM replaceCharactersInRange:checkResult.range withString:@""];
            self.msgTextView.text = txtStrM;
            //光标前移
            self.msgTextView.selectedRange = NSMakeRange(location - checkResult.range.length, 0);
            deleteEmotion = YES;
            *stop = YES;
        }
    }];
    
    //如果光标前没有表情
    if (!deleteEmotion) {
        [txtStrM replaceCharactersInRange:NSMakeRange(txtStrM.length-1, 1) withString:@""];
        self.msgTextView.text = txtStrM;
        //光标前移
        self.msgTextView.selectedRange = NSMakeRange(location - 1, 0);
    }
}
#pragma mark - 发送文本/表情消息
- (void)sendTextMessage{
    
    if ([LSAccountArchive isLogin] == NO) {
        self.block();
        return;
    }
    //回调
    if (_textCallback) {
        _textCallback(self.msgTextView.text);
        self.msgTextView.text = @"";
        //更新输入框
        [self msgTextViewHeightFit:defaultInputHeight];
    }
}
- (void)textCallback:(ChatTextMessageSendBlock)textCallback target:(id)target{
    
    _textCallback = textCallback;
    
    _target = target;
}



- (void)dealloc{
    [self.msgTextView removeObserver:self forKeyPath:@"contentSize"];
}

#pragma mark - 键盘降落
- (void)keyboardResignFirstResponder:(NSNotification *)note{
    NSInteger KeyH = 0;
    if ([note.object integerValue] == 1) {
        KeyH = 100 + LSScareValue(200, LSScreenWidth) -LSNavBarHeight;
    }else if([note.object integerValue] == 2){
        
        KeyH = LSNavBarHeight;
    }
    [self.msgTextView resignFirstResponder];
    //按钮初始化刷新
    [self reloadSwitchButtons];
    CGFloat  heigth = Height(self.messageBar.frame);
    
    //305
    [self customKeyboardMove:LSScreenHeight - KeyH  - heigth];
    if (_changHback) {
        self.changHback(0);
    }
}

-(void)keyboardChangeBack:(ChatBoardChangeBlock)changHBack target:(id)target{
    
    _changHback =changHBack;
    _target = target;
}

@end
